<template>
    <view class="doll-detail">
        <!-- 顶部导航 -->
        <view class="nav-bar">
            <view class="nav-left">
                <uni-icons @click="goBack" type="left" size="20" color="#333333"></uni-icons>
            </view>
            <view class="nav-title">娃娃详情</view>
            <view class="nav-right">
                <uni-icons @click="toggleEdit" :type="isEdit ? 'checkbox' : 'gear'" size="20"
                    color="#333333"></uni-icons>
            </view>

        </view>
<!--        <view class="info-section">-->
<!--          <view class="info-item">-->
<!--            <text class="label">娃娃相册</text>-->
<!--          </view>-->
<!--        </view>-->
        <!-- 主要内容区域 -->
        <scroll-view class="content" scroll-y>
            <!-- 娃娃照片展示区 -->
          <view class="info-section">
            <view class="info-item">
              <text class="label">娃娃相册</text>
              <view class="photo-section">
                <scroll-view scroll-x class="media-scroll">
                  <view class="media-list" v-if="mediaList.length > 0">
                    <view v-for="(item, index) in mediaList" :key="index" class="media-item">
                      <image v-if="item.type === 'image'" class="media-content" :src="item.url" mode="aspectFill"
                             @click="previewMedia(index)"></image>
                      <video v-else class="media-content" :src="item.url" controls></video>
                      <view v-if="isEdit" class="delete-media" @click.stop="deleteMedia(index)">
                        <uni-icons type="closeempty" size="20" color="#ffffff"></uni-icons>
                      </view>
                    </view>
                  </view>
                  <view v-else class="empty-media">
                    <uni-icons type="image" size="50" color="#FFB6C1"></uni-icons>
                    <text class="empty-text">{{ isEdit ? '点击下方按钮上传图片或视频' : '暂无图片或视频' }}</text>
                  </view>
                </scroll-view>
                <view v-if="isEdit" class="media-actions">

                  <button class="save-btn" type="primary" @click="chooseImage">点击上传 {{percentage}}</button>

                </view>
              </view>
            </view>
          </view>

            <!-- 基础信息区域 -->
            <view class="info-section">
                <view class="info-item">
                    <text class="label">娃娃取名</text>
                    <input v-if="isEdit" v-model="dollInfo.name" class="input" placeholder="请输入娃娃名称" />
                    <text v-else class="value">{{ dollInfo.name }}</text>
                </view>
                <view class="info-item">
                    <text class="label">娃娃ID</text>
                    <text class="value readonly">{{ dollInfo.dollNo }}</text>
                </view>
<!--                <view class="info-item">-->
<!--                    <text class="label">尺寸信息</text>-->
<!--                    <text class="value readonly">{{ dollInfo.size }}</text>-->
<!--                </view>-->
            </view>
            <!-- 详细信息区域 -->
            <view class="detail-section">
                <view class="detail-item">
                    <text class="label">娃娘信息</text>
                    <view class="owner-info">
                        <view class="owner-item">
                            <text class="owner-label">姓名：</text>
                            <text class="value readonly">{{ dollInfo.owner.name }}</text>

                        </view>
                        <view class="owner-item">
                            <text class="owner-label">电话：</text>
                            <text class="value readonly">{{ dollInfo.owner.phone }}</text>
                        </view>
                    </view>
                </view>
<!--                <view class="detail-item">-->
<!--                    <text class="label">订单物流</text>-->
<!--                    <view class="logistics-info">-->
<!--                        <view class="logistics-item">-->
<!--                            <text class="logistics-label">订单编号：</text>-->
<!--                            <text class="value readonly">{{ dollInfo.logistics.orderNo }}</text>-->

<!--                        </view>-->
<!--                        <view class="logistics-item">-->
<!--                            <text class="logistics-label">快递单号：</text>-->
<!--                            <text class="value readonly">{{ dollInfo.logistics.trackingNo }}</text>-->
<!--                            -->
<!--                        </view>-->
<!--                    </view>-->
<!--                </view>-->
            </view>
        </scroll-view>
        <!-- 底部操作区 -->
        <view v-if="isEdit" class="bottom-actions">
            <button class="save-btn" type="primary" @click="saveDollInfo">保存修改</button>
        </view>
    </view>
</template>
<script setup>
import { ref, reactive ,onMounted } from 'vue';
import { appOrderApi } from '@/api/business/bjd/app-order-api';
import { appDollApi } from '@/api/business/bjd/app-doll-api';
import { fileApi } from '@/api/support/file-api';
import { FILE_FOLDER_TYPE_ENUM } from '@/constants/support/file-const';
import { smartSentry } from '@/lib/smart-sentry';
import _ from 'lodash';
import { SmartLoading, SmartToast } from '@/lib/smart-support';


onMounted(() => {
    console.log("开始加载成功");
    //uni 获取url中dollNo参数
    const pages = getCurrentPages();
    const currentPage = pages[pages.length - 1];
    const orderNo = currentPage.options.orderNo;
    loadDetail(orderNo);
});
const percentage = ref("");
function loadDetail(orderNo){
  console.log(orderNo);

  const param = {
    orderNo:orderNo
  }
  // 调用接口获取娃娃详情
  appDollApi.detail(param).then(response => {
    console.log(response);

    dollInfo.dollNo = response.data.dollNo;
    dollInfo.type = response.data.type;
    dollInfo.size = response.data.size;
    dollInfo.officialName = response.data.officialName;
    if(response.data.userNickName !== ''){
      dollInfo.name = response.data.userNickName
    }else{
      dollInfo.name = '';
    }

    dollInfo.owner.name = response.data.dollName;
    dollInfo.owner.phone = response.data.dollPhone;

    dollInfo.logistics.orderNo = response.data.orderNo;
    dollInfo.logistics.trackingNo = response.data.logisticsNo;

    //先清空mediaList
    mediaList.value = [];
    if(response.data.albumImageArray != null && response.data.albumImageArray.length > 0){
      response.data.albumImageArray.forEach((item) => {
        // 如果 item.imageType == 1 表示图片 imageType == 2 表示视频
        if (item.imageType === 1) {
          mediaList.value.push({
            type: 'image',
            url: item.imageUrl
          });
        } else {
          mediaList.value.push({
            type: 'video',
            url: item.imageUrl
          });
        }
      });
    }
    percentageAuto();

    // 其他属性的更新...
  }).catch(error => {
    console.error('Error fetching doll details:', error);
  });
}

const mediaList = ref([
    // {
    //     type: 'image',
    //     url: 'https://ai-public.mastergo.com/ai/img_res/f3d2cc4a24e44f679ca9ceee04b05450.jpg'
    // }
]);

const uploadList = ref([]);

const isEdit = ref(true);
const dollInfo = reactive({
    id:'',
    dollNo: 'DOLL20240101001',
    officialName: '',
    name:'',
    purchaseDate: '2024-01-01',
    type: '温暖牌',
    description: '这是一个非常可爱的布偶娃娃，有着柔软的毛发和温暖的笑容。它是孩子们最好的玩伴，能带给他们无限的欢乐和温暖。',
    size: '30cm x 15cm x 10cm',
    skin: '优质棉布、环保填充物',
    owner: {
        name: '小美',
        phone: '13800138000'
    },
    logistics: {
        orderNo: '顺丰速运',
        trackingNo: 'SF1234567890123'
    }
});
const goBack = () => {
    uni.navigateBack();
};
const toggleEdit = () => {
    isEdit.value = !isEdit.value;
};

function percentageAuto(){
  percentage.value = mediaList.value.length+"/"+100;
}

// 新增方法，替换原来的 onSelectFile
function chooseImage() {
  uni.chooseImage({
    count: 9, // 最多可以选择的图片张数
    sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
    sourceType: ['album'], // 从相册选择
    success: function (res) {
      console.log("选择图片成功：", res.tempFilePaths);
      // 循环上传选中的图片
      for (const tempFilePath of res.tempFilePaths) {
        upload(tempFilePath);
      }
    },
    fail: function(err) {
      console.error("选择图片失败：", err);
    }
  });
}

function onSelectFile(param) {
    console.log("开始选择上传", param);
    let tempFilePaths = param.tempFilePaths;

    console.log("获取到文件路径：", tempFilePaths);
    for (const tempFilePath of tempFilePaths) {
      upload(tempFilePath);
    }
}

  async function upload(tempFilePath) {
    try {
      SmartLoading.show();
      let res = await fileApi.upload(tempFilePath, FILE_FOLDER_TYPE_ENUM.COMMON.value);
      res.data.tempFilePath = tempFilePath;
      //判断是否是图片
      // 创建新数组并替换原数组，触发视图更新
      const newMediaList = [...mediaList.value];

      if (res.data.fileType === 'png' || res.data.fileType === 'jpg' || res.data.fileType === 'jpeg') {
        newMediaList.push({ type: 'image', url: res.data.fileUrl });
      } else {
        newMediaList.push({ type: 'video', url: res.data.fileUrl });
      }
      mediaList.value = newMediaList;
      percentageAuto();

    } catch (e) {
      smartSentry.captureError(e);
    } finally {
      SmartLoading.hide();
    }
  }

  function onDeleteFile(param) {
    if (!param.tempFilePath) {
      return;
    }
    _.remove(uploadList.value, (e) => e.tempFilePath === param.tempFilePath);
  }

const deleteMedia = (index) => {
    mediaList.value.splice(index, 1);
    console.log('删除媒体资源：', index);
    percentageAuto();

};
const previewMedia = (index) => {
    const item = mediaList.value[index];
    if (item.type === 'image') {
        const imageUrls = mediaList.value
            .filter(item => item.type === 'image')
            .map(item => item.url);
        uni.previewImage({
            current: item.url,
            urls: imageUrls
        });
    }
};

const saveDollInfo = () => {
    if (!dollInfo.name?.trim()) {
      uni.showToast({
        title: '娃娃名称不能为空',
        icon: 'none'
      });
      return;
    }
    uni.showLoading({ title: '保存中' });
    setTimeout(() => {
        uni.hideLoading();
        
        if(dollInfo.name !== ''){
            console.log('更新nickName:', dollInfo);
            var param = {
                orderNo:dollInfo.logistics.orderNo,
                userNickName:dollInfo.name
            }
            appDollApi.nickName(param);
        }
        

        console.log('保存媒体资源：', mediaList.value);
        var albumImageArray = [];
        mediaList.value.forEach((item) => {
            albumImageArray.push({
                imageType: item.type === 'image' ? 1 : 2,
                imageUrl: item.url
            });
        });
        var albumParam = {
            orderNo:dollInfo.logistics.orderNo,
            albumImageArray:albumImageArray
        }
        appDollApi.album(albumParam);


        uni.showToast({
            title: '保存成功',
            icon: 'success'
        });

        isEdit.value = false;
    }, 1500);
};



</script>
<style>
page {
    height: 100%;
}

.doll-detail {
    height: 100%;
    display: flex;
    flex-direction: column;
    background-color: #f8f8f8;
}

.nav-bar {
    margin-top: 150rpx;
    height: 88rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 30rpx;
    background-color: #ffffff;
    border-bottom: 1px solid #f0f0f0;
    flex-shrink: 0;
}

.nav-left,
.nav-right {
    width: 40px;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.nav-title {
    font-size: 16px;
    font-weight: 500;
    color: #333333;
}

.content {
    flex: 1;
    overflow: auto;
}

.photo-section {
    position: relative;
    width: 100%;
    background-color: #ffffff;
    padding: 20rpx 0;
}

.media-scroll {
    width: 100%;
    white-space: nowrap;
}

.media-list {
    padding: 0 0;
    display: inline-flex;
}

.media-item {
    position: relative;
    width: 400rpx;
    height: 400rpx;
    margin-right: 20rpx;
    border-radius: 12px;
    overflow: hidden;
}

.media-content {
    width: 100%;
    height: 400rpx;
    object-fit: cover;
}

.empty-media {
    width: 100%;
    height: 400rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-color: #FFF9FA;
    border-radius: 12px;
    margin: 0 20rpx;
}

.empty-text {
    margin-top: 20rpx;
    font-size: 28rpx;
    color: #FF6B8B;
    text-align: center;
}

.delete-media {
    position: absolute;
    top: 10rpx;
    right: 10rpx;
    width: 40rpx;
    height: 40rpx;
    border-radius: 20rpx;
    background-color: rgba(255, 107, 139, 0.8);
    display: flex;
    align-items: center;
    justify-content: center;
}

.media-actions {
    margin-top: 20rpx;
    padding: 0 20rpx;
    display: flex;
    gap: 20rpx;
}

.action-btn {
    flex: 1;
    height: 80rpx;
    background-color: rgba(255, 107, 139, 0.8);
    border-radius: 40rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 10rpx;
}

.action-text {
    font-size: 14px;
    color: #ffffff;
}

.info-section,
.detail-section {
    margin: 20rpx;
    padding: 30rpx;
    background-color: #ffffff;
    border-radius: 12px;
    box-shadow: 0 4rpx 12rpx rgba(255, 107, 139, 0.1);
}

.info-item,
.detail-item {
    margin-bottom: 30rpx;
}

.info-item:last-child,
.detail-item:last-child {
    margin-bottom: 0;
}

.label {
    display: block;
    font-size: 14px;
    color: #FF6B8B;
    margin-bottom: 16rpx;
}

.value {
    display: block;
    font-size: 16px;
    color: #666666;
    line-height: 1.5;
}

.readonly {
    color: #999999;
}

.input {
    width: 100%;
    height: 80rpx;
    border: 1px solid #FFE4E9;
    border-radius: 8px;
    padding: 0 20rpx;
    font-size: 16px;
    background-color: #FFF9FA;
}

.textarea {
    width: 100%;
    height: 160rpx;
    border: 1px solid #FFE4E9;
    border-radius: 8px;
    padding: 20rpx;
    font-size: 16px;
    background-color: #FFF9FA;
}

.picker-value {
    width: 100%;
    height: 80rpx;
    line-height: 80rpx;
    border: 1px solid #FFE4E9;
    border-radius: 8px;
    padding: 0 20rpx;
    font-size: 16px;
    background-color: #FFF9FA;
}

.description {
    line-height: 1.6;
}

.owner-info {
    margin-top: 10rpx;
}

.owner-item {
    margin-bottom: 20rpx;
    display: flex;
    align-items: center;
}

.owner-item:last-child {
    margin-bottom: 0;
}

.owner-label {
    font-size: 14px;
    color: #999999;
    width: 100rpx;
    flex-shrink: 0;
}

.owner-value {
    font-size: 14px;
    color: #333333;
    flex: 1;
}

.logistics-info {
    margin-top: 10rpx;
}

.logistics-item {
    margin-bottom: 20rpx;
    display: flex;
    align-items: center;
}

.logistics-item:last-child {
    margin-bottom: 0;
}

.logistics-label {
    font-size: 14px;
    color: #999999;
    width: 140rpx;
    flex-shrink: 0;
}

.logistics-value {
    font-size: 14px;
    color: #333333;
    flex: 1;
}

.logistics-value.status {
    color: #52C41A;
}

.bottom-actions {
    padding: 20rpx 30rpx 40rpx;
    background-color: #ffffff;
    border-top: 1px solid #FFE4E9;
    flex-shrink: 0;
}

.save-btn {
    margin-bottom: 20rpx;
    background-color: #FF6B8B !important;
    border-color: #FF6B8B !important;
}

.delete-btn {
    margin: 0;
    border-color: #FFE4E9 !important;
    background-color: #FFF5F7 !important;
    color: #FF6B8B !important;
}

.uni-file-picker__lists {
  position: relative;
  margin-top: 5px;
  overflow: hidden;
  display: none;
}
</style>